package com.zmjmall.demo.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zmjmall.demo.config.QiniuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;

/**
 * @author zmj
 * @version 2018/7/17
 */
@Component
@Slf4j
public class QiniuUtil {

    @Autowired
    private QiniuConfig qiniuConfig;

    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.autoZone());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);


    public String getUpToken() {
        Auth auth = Auth.create(qiniuConfig.getAccesskey(), qiniuConfig.getSecretkey());
        return auth.uploadToken(qiniuConfig.getBucket());
    }

    public Auth getbucketToken() {
        return   Auth.create(qiniuConfig.getAccesskey(), qiniuConfig.getSecretkey());
    }
    /**
     * 将图片上传到七牛云
     * @param file
     * @param key 保存在空间中的名字，如果为空会使用文件的hash值为文件名
     * @return
     */
    public  String uploadImg(FileInputStream file, String key,String suffix) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.autoZone());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            Auth auth = Auth.create(qiniuConfig.getAccesskey(), qiniuConfig.getSecretkey());
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            try {
                Response response = uploadManager.put(file, key, upToken,null,suffix);
                //解析上传成功的结果
               // DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                String return_path = qiniuConfig.getPath()+"/"+putRet.key;
                log.info("保存地址={}",return_path);
                return return_path;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 覆盖上传
     * @param path
     *            上传文件路径
     * @param bucketName
     *            空间名
     * @param key
     *            文件名
     */
    public void overrideUpload(String path, String bucketName, String key) {
        try {
            String token = getUpToken();//获取 token
            Response response = uploadManager.put(path, key, token);//执行上传，通过token来识别 该上传是“覆盖上传”
            System.out.println(response.toString());
        } catch (QiniuException e) {
            System.out.println(e.response.statusCode);
            e.printStackTrace();
        }
    }

    public void delete(String key) {
        BucketManager bucketManager = new BucketManager(getbucketToken(), cfg);
        try {
            bucketManager.delete(qiniuConfig.getBucket(), key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            log.error("异常错误码:" + ex.code() + ",异常信息:" + ex.response.toString());
        }

    }

    //base64方式上传
    public  String put64image(byte[] base64, String key){
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone1());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传

        try {
            Auth auth = Auth.create(qiniuConfig.getAccesskey(), qiniuConfig.getSecretkey());
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            try {
                Response response = uploadManager.put(base64, key, upToken);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                String returnPath = qiniuConfig.getPath() + "/" + putRet.key;
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                log.error(r.toString());
                try {
                    log.error(r.bodyString());
                } catch (QiniuException ex2) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
